package cn.edu.sysu.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.sysu.dao.IssueDao;
import cn.edu.sysu.dao.SolutionDao;
import cn.edu.sysu.dto.IssueDto;
import cn.edu.sysu.dto.SolutionDto;
import cn.edu.sysu.mail.MailUtil;
import cn.edu.sysu.service.UserService;
import cn.edu.sysu.util.Transaction;
import cn.edu.sysu.util.TransactionRead;
import cn.edu.sysu.util.TransactionWrite;

public class SaveServlet extends HttpServlet {

	SolutionDao sDao = SolutionDao.INSTANCE;
	IssueDao iDao = IssueDao.INSTANCE;
	UserService uService = new UserService();

	Transaction read = TransactionRead.INSTANCE;
	Transaction write = TransactionWrite.INSTANCE;

	MailUtil mailUtil = MailUtil.INSTANCE;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String method = req.getParameter("method");

		if ("saveSolution".equals(method)) {
			int user_id = Integer.parseInt(req.getParameter("user_id"));
			String code = req.getParameter("code");
			int problem_id = Integer.parseInt(req.getParameter("problem_id"));

			SolutionDto sd = new SolutionDto(code, new Date(System.currentTimeMillis()), problem_id, 1, user_id, 99);
			int nextRevision;
			try {
				nextRevision = sDao.getNextRevisionNumber(read, sd);
				sd.setRevision(nextRevision);

				sDao.saveSolution(write, sd);

				//mailUtil.SendSolutionPostMail(uService.getUserById(user_id), sd);

			} catch (SQLException e) {

				e.printStackTrace();
			}
		} else if ("saveIssue".equals(method)) {
			int solution_user_id = Integer.parseInt(req.getParameter("solution_user_id"));
			String issue = req.getParameter("issue");
			int problem_id = Integer.parseInt(req.getParameter("problem_id"));
			int revision = Integer.parseInt(req.getParameter("revision"));
			int issue_user_id = Integer.parseInt(req.getParameter("issue_user_id"));
			int reply_to = -1;
			int correct = Integer.parseInt(req.getParameter("correctness"));
			if (req.getParameter("reply_to") != null) {
				reply_to = Integer.parseInt(req.getParameter("reply_to"));
			}

			IssueDto is = new IssueDto(solution_user_id, problem_id, revision, issue, issue_user_id, reply_to,
					new Date(System.currentTimeMillis()));
			//System.out.println(is.getPost_time());
			iDao.saveIssue(write, is);
			sDao.updateCorrectness(write, solution_user_id, problem_id, revision, correct);

		} else if ("register".equals(method)) {
			String email = req.getParameter("email");
			boolean success = uService.createUser(email);
			if(success){
				res.getWriter().print("{\"success\":1}");
			}
			else{
				res.getWriter().print("{\"success\":0, \"reason\":\"Email address already exists\"}");
			}
			res.setContentType("text/JSON");
		}
	}
}
